/**
 * Copyright 2011 Sibaozuan(superskysbz@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package summary.android.async;

import java.util.List;

import summary.android.activity.R;
import summary.android.async.AsyncImageLoader.ImageCallback;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
/**
 * 
 * @author Sibaozuan(superskysbz@gmail.com)
 *
 */
public class ImageAndTextListAdapter extends ArrayAdapter<ImageAndText> {
	private ListView listView;
	private AsyncImageLoader asyncImageLoader;

	public ImageAndTextListAdapter(Activity activity, List<ImageAndText> imageAndTexts,
			ListView listView) {
		super(activity, 0, imageAndTexts);
		this.listView = listView;
		asyncImageLoader = new AsyncImageLoader();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Activity activity = (Activity) getContext();
		// Inflate the views from XML
		View rowView = convertView;
		// 用于缓存ListView中的每个列View，以减少解析XML文件的时间
		ViewCache viewCache;
		// 如果rowView为空，需解析MXL文件，并放入ViewCache缓存，否则，直接从缓存中获取
		if (rowView == null) {
			LayoutInflater inflater = activity.getLayoutInflater();
			rowView = inflater.inflate(R.layout.async_image_row, null);
			viewCache = new ViewCache(rowView);
			rowView.setTag(viewCache);
		} else {
			viewCache = (ViewCache) rowView.getTag();
		}

		ImageAndText imageAndText = getItem(position);

		String imageUrl = imageAndText.getImageUrl();
		ImageView imageView = viewCache.getImageView();
		imageView.setTag(imageUrl);
		Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl, new ImageCallback() {
			public void imageUpdated(Drawable imageDrawable, String imageUrl) {
				ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
				// 图片刚从远程下载完后，是通过回调接口直接放入ImageView中显示的
				// 若图片缓存中已有了此图片，则不会调用此回调方法
				if (imageViewByTag != null) {
					imageViewByTag.setImageDrawable(imageDrawable);
				}
			}
		});
		if (cachedImage != null) {
			imageView.setImageDrawable(cachedImage);
		}

		// Set the text on the TextView
		TextView textView = viewCache.getTextView();
		textView.setText(imageAndText.getText());

		return rowView;
	}
}
